package com.changgou.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.changgou.canal.config.RabbitMQConfig;
import com.changgou.canal.util.CanalUtils;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * @Author: HuangFu
 * @Date: 2020/1/31 11:58
 * @Description: 广告数据监听
 */
@CanalEventListener //设置Canal监听
public class AdListener {

    private final static String AD_POSITION = "position";


    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     *
     * @param entryType 当前操作数据库的类型
     * @param rowData  当前操作的数据行
     */
    @ListenPoint(schema = "changgou_business" , table = "tb_ad")
    public void adUpdate(CanalEntry.EntryType entryType, CanalEntry.RowData rowData){
        //数据行修改之前
        //rowData.getBeforeColumnsList().forEach(c-> System.out.println("改变前的数据:"+c.getName()+"::"+c.getValue()));

        //数据行修改之后
        //rowData.getAfterColumnsList().forEach((c)-> System.out.println("改变之后的数据:"+c.getName()+"::"+c.getValue()));

        //获取修改之前数据
        Map<String, String> beforeMap = CanalUtils.convertToMap(rowData.getBeforeColumnsList());
        //获取修改之后
        Map<String, String> afterMap = CanalUtils.convertToMap(rowData.getAfterColumnsList());

        //获取广告位置修改之前数据
        String beforePosition = beforeMap.get(AD_POSITION);
        //获取广告位置修改之后数据
        String afterPosition = afterMap.get(AD_POSITION);
        if(beforePosition !=null){
            System.out.println("beforePosition发送消息到mq");
            rabbitTemplate.convertAndSend("", RabbitMQConfig.AD_UPDATE_QUEUE,beforePosition);
        }
        //修改数据不为空，且与之前数据不相同
        if(afterPosition!=null && !afterPosition.equals(beforePosition)){
            System.out.println("afterPosition发送消息到mq");
            rabbitTemplate.convertAndSend("", RabbitMQConfig.AD_UPDATE_QUEUE,afterPosition);
        }



    }

}
